<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>师门记录器</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    body {
      font-family: '微软雅黑', Arial, sans-serif;
      background: linear-gradient(135deg, #e0e7ff 0%, #f5f6fa 100%);
      margin: 0;
      padding: 0;
      min-height: 100vh;
    }
    h1 {
      text-align: center;
      margin: 24px 0 18px 0;
      font-size: 2.1em;
      font-weight: 900;
      letter-spacing: 2px;
      color: #222;
      text-shadow: 0 2px 8px #e0e7ff;
    }
    .container {
      max-width: 900px;
      margin: 0 auto;
      padding: 10px 2px 10px 2px; /* 只保留很小的底部padding，避免内容紧贴底部 */
      background: #fafdff;
      border-radius: 18px;
      box-shadow: 0 4px 32px 0 rgba(64,158,255,0.10), 0 1.5px 6px 0 rgba(0,0,0,0.04);
      min-height: 100vh;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: flex-start;
    }
    .roles-2col {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 12px;
      justify-content: center;
      align-items: stretch;
      width: 100%;
      margin: 0 auto;
      max-width: 440px;
    }
    .roles-row {
      display: contents;
    }
    .roles-cell {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: stretch;
    }
    .role-card {
      background: #eaf4ff;
      border-radius: 16px;
      box-shadow: 0 2px 12px 0 rgba(64,158,255,0.10), 0 1.5px 6px 0 rgba(0,0,0,0.04);
      padding: 6px 2px 6px 2px;
      width: 97%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: flex-start;
      position: relative;
      border: 2.5px solid transparent;
      transition: box-shadow 0.2s, border 0.2s, background 0.2s;
      min-height: 48px;
      margin: 0 auto;
      margin-bottom: 2px;
      cursor: pointer;
      user-select: none;
    }
    .status-dot {
      position: absolute;
      top: 8px;
      right: 10px;
      width: 14px;
      height: 14px;
      border-radius: 50%;
      box-shadow: 0 1px 4px rgba(0,0,0,0.08);
      border: 2px solid #fff;
      z-index: 2;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .status-dot.active {
      background: #67c23a;
    }
    .status-dot.pause {
      background: #f56c6c;
    }
    .role-progress-row {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      margin-bottom: 6px;
      font-size: 1.08em;
      font-weight: 500;
    }
    .role-card.active-role {
      border: 2.5px solid #409eff;
      background: linear-gradient(135deg, #e6f7ff 60%, #eaf4ff 100%);
      box-shadow: 0 4px 18px rgba(64,158,255,0.18);
    }
    .role-card.inactive-role {
      background: #f5f5f5;
      border: 2px solid #d3d3d3;
      color: #aaa;
      box-shadow: none;
      opacity: 0.92;
    }
    .role-card:active {
      box-shadow: 0 0 0 2px #409eff33;
      filter: brightness(0.98);
    }
    .role-name {
      font-size: 1.13em;
      font-weight: bold;
      margin-bottom: 6px;
      padding: 2px 4px;
      border-radius: 4px;
      transition: background 0.2s;
      word-break: break-all;
      text-align: center;
      letter-spacing: 1px;
      color: #222;
    }
    .role-name.editing {
      background: #fffbe6;
      border: 1px solid #ffe58f;
    }
    .role-progress, .role-timer {
      margin: 0;
      font-size: 1em;
    }
    .btns {
      display: flex;
      gap: 10px;
      margin-bottom: 8px;
      width: 100%;
      justify-content: center;
    }
    button {
      padding: 7px 0;
      min-width: 44px;
      border: none;
      border-radius: 8px;
      background: #409eff;
      color: #fff;
      cursor: pointer;
      font-size: 1.13em;
      font-weight: 600;
      transition: background 0.2s, box-shadow 0.2s;
      box-shadow: 0 1px 4px rgba(64,158,255,0.08);
      outline: none;
    }
    .btn-add {
      background: #67c23a;
      color: #fff;
      border: none;
      font-size: 1.13em;
      min-width: 44px;
      border-radius: 8px;
      box-shadow: 0 1px 4px rgba(103,194,58,0.08);
    }
    .btn-sub {
      background: #f56c6c;
      color: #fff;
      border: none;
      font-size: 1.13em;
      min-width: 44px;
      border-radius: 8px;
      box-shadow: 0 1px 4px rgba(245,108,108,0.08);
    }
    .btn-cancel {
      background: #e4e7ed;
      color: #666;
      font-size: 0.98em;
      min-width: 70px;
      padding: 4px 0;
      border-radius: 7px;
      margin-top: 10px;
      margin-bottom: 0;
      box-shadow: 0 1px 2px rgba(0,0,0,0.03);
      border: none;
      transition: background 0.2s, color 0.2s;
    }
    .btn-cancel:active {
      background: #d3d6db;
      color: #444;
    }
    .btn-cancel:disabled {
      background: #f0f0f0;
      color: #bbb;
    }
    .cancel-section {
      margin-top: 2px;
      font-size: 0.98em;
      color: #e67e22;
      min-height: 18px;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 22px;
      font-weight: 500;
      letter-spacing: 1px;
    }
    .cancel-placeholder {
      opacity: 0;
      pointer-events: none;
      height: 32px;
      margin-top: 8px;
      display: block;
    }
    @media (max-width: 900px) {
      .roles-2col {
        grid-template-columns: 1fr 1fr;
        gap: 4px;
        max-width: 99vw;
      }
    }
    @media (max-width: 600px) {
      .container {
        padding: 1vw;
      }
      .roles-2col {
        grid-template-columns: 1fr 1fr;
        gap: 2px;
        max-width: 99vw;
      }
      .role-card {
        width: 99%;
        min-width: 0;
        max-width: 100vw;
        padding: 2px 1px 2px 1px;
        min-height: 36px;
      }
      .role-name {
        font-size: 0.98em;
        margin-bottom: 2px;
      }
      .role-progress-row {
        font-size: 0.92em;
        margin-bottom: 2px;
      }
      .btns button, .btn-add, .btn-sub {
        font-size: 1em;
        min-width: 36px;
        padding: 4px 0;
      }
      .btns {
        gap: 6px;
        margin-bottom: 4px;
      }
      .cancel-section {
        font-size: 0.88em;
        height: 14px;
        min-height: 10px;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="roles-2col" id="roles-col-1"></div>
  </div>
  <div style="height: 90px;"></div>
  <div class="footer-bar" id="footer-bar">
    <button id="btn-reset-all">全部重置</button>
    <button id="btn-toggle-pause">暂停</button>
    <span class="day-total-timer">今日总耗时：<span id="day-total-time">00:00:00</span></span>
    <button id="btn-clear-cache">清空缓存</button>
  </div>
  <script>
    const ROLE_COUNT = 10;
    const MAX_TASKS = 20;
    const CANCEL_TIME = 5 * 60; // 5分钟，单位秒
    const STORAGE_KEY = 'xyq_shimen_progress_v2';

    // 新增：每个角色有 isActive(是否进行中)、totalTime(累计用时秒)、lastStart(最后开始计时的时间戳)
    function getDefaultRoles() {
      // 默认角色名常量
      const DEFAULT_ROLE_NAMES = [
        '化生', '凌波', '女儿村', '龙宫', '地府',
        '大女儿', '二女儿', '三女儿', '四女儿', '小女儿'
      ];
      return Array.from({length: ROLE_COUNT}, (_, i) => ({
        name: DEFAULT_ROLE_NAMES[i],
        progress: 0,
        cancelUntil: 0,
        isActive: i < 5, // 前5个进行中
        totalTime: 0,    // 累计用时（秒）
        lastStart: i < 5 ? Date.now() : null, // 进行中则有开始时间
        isFinished: false, // 是否已完成
        finishedProgress: null, // 新增：完成时的进度
        finishedTime: 0 // 新增：完成时的总耗时
      }));
    }

    function loadData() {
      const data = localStorage.getItem(STORAGE_KEY);
      if (data) {
        try {
          const parsed = JSON.parse(data);
          if (Array.isArray(parsed.roles)) {
            // 兼容旧数据
            if (!('isActive' in parsed.roles[0])) {
              // 升级旧数据
              parsed.roles.forEach((r, i) => {
                r.isActive = i < 5;
                r.totalTime = 0;
                r.lastStart = r.isActive ? Date.now() : null;
              });
            }
            return parsed;
          }
        } catch {}
      }
      return { roles: getDefaultRoles() };
    }

    function saveData(data) {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
    }

    let { roles } = loadData();
    // 全局暂停相关
    let isPaused = false;
    let pauseStartTime = null;
    let totalPausedTime = 0; // 单位：毫秒
    // 尝试从localStorage恢复
    const PAUSE_KEY = 'xyq_shimen_pause_v2';
    function loadPause() {
      const data = localStorage.getItem(PAUSE_KEY);
      if (data) {
        try {
          const parsed = JSON.parse(data);
          isPaused = !!parsed.isPaused;
          pauseStartTime = parsed.pauseStartTime || null;
          totalPausedTime = parsed.totalPausedTime || 0;
        } catch {}
      }
    }
    function savePause() {
      localStorage.setItem(PAUSE_KEY, JSON.stringify({isPaused, pauseStartTime, totalPausedTime}));
    }
    loadPause();
    // 页面加载时根据isPaused设置按钮文本
    window.addEventListener('DOMContentLoaded', function() {
      document.getElementById('btn-toggle-pause').textContent = isPaused ? '恢复' : '暂停';
    });

    // 渲染两列
    function renderRoles() {
      const now = Date.now();
      let html = '';
      for (let i = 0; i < 5; i++) {
        html += `<div class='roles-row'>
          <div class='roles-cell'>${renderRoleCard(roles[i], i, now)}</div>
          <div class='roles-cell'>${renderRoleCard(roles[i+5], i+5, now)}</div>
        </div>`;
      }
      document.getElementById('roles-col-1').innerHTML = html;
      bindEvents();
      // 卡片点击切换
      document.querySelectorAll('.role-card').forEach(card => {
        card.onclick = function(e) {
          // 避免点击按钮或名字时触发切换
          if (
            e.target.tagName === 'BUTTON' ||
            e.target.classList.contains('btn-add') ||
            e.target.classList.contains('btn-sub') ||
            e.target.classList.contains('btn-cancel') ||
            e.target.classList.contains('role-name')
          ) return;
          const idx = +card.dataset.idx;
          // 只有未进行中的卡片才允许切换
          if (roles[idx].isActive) return;
          const row = idx % 5;
          switchRoles(row);
        };
      });
      // 名字编辑阻止冒泡
      document.querySelectorAll('.role-name').forEach(el => {
        el.onclick = function(e) {
          e.stopPropagation();
          startEditName(+el.dataset.idx);
        };
      });
    }

    function renderRoleCard(role, idx, now) {
      // 完成状态只显示名字和《已完成师门》和还原按钮，并显示总耗时
      if (role.isFinished) {
        // 计算最终总耗时
        let total = role.totalTime;
        // 如果lastStart有值，说明完成时未累加，需加上
        if (role.lastStart) {
          total += (role.finishedTime || 0);
        }
        // 但实际上完成时已累加totalTime，直接用totalTime即可
        return `
          <div class="role-card finished-role" data-idx="${idx}">
            <div class="role-name" data-idx="${idx}" tabindex="0">${escapeHtml(role.name)}</div>
            <div class="finished-label">《已完成师门》</div>
            <div class="finished-time">总耗时：${formatTime(Math.floor(role.totalTime))}</div>
            <button class="btn-restore" data-idx="${idx}">还原</button>
          </div>
        `;
      }
      // 复用原有渲染逻辑
      // 复制自renderRoleRow的单卡片部分
      let cancelBtn = '', cancelSection = '';
      const canceling = role.cancelUntil > now;
      cancelBtn = role.isActive
        ? `<button class="btn-cancel" data-idx="${idx}" ${canceling?'disabled':''}>取消任务</button>`
        : `<button class="btn-cancel cancel-placeholder" tabindex="-1" disabled>取消任务</button>`;
      cancelSection = `<div class="cancel-section">${canceling ? `等待取消：<span class="countdown" data-idx="${idx}">${formatTime(Math.max(0, Math.ceil((role.cancelUntil-now)/1000)))}</span>` : '&nbsp;'}</div>`;
      return `
        <div class="role-card ${role.isActive ? 'active-role' : 'inactive-role'}" data-idx="${idx}">
          <span class="status-dot ${role.isActive ? 'active' : 'pause'}"></span>
          <div class="role-name" data-idx="${idx}" tabindex="0">${escapeHtml(role.name)}</div>
          <div class="role-progress-row">
            <span class="role-progress">${role.progress} / ${MAX_TASKS}</span>
            <span class="role-timer">${formatTime(getTotalTime(role, now))}</span>
          </div>
          <div class="btns">
            <button class="btn-add" data-idx="${idx}" ${role.progress>=MAX_TASKS?'disabled':''}>+1</button>
            <button class="btn-sub" data-idx="${idx}" ${role.progress<=0?'disabled':''}>-1</button>
            <button class="btn-finish" data-idx="${idx}">完成</button>
          </div>
          ${cancelBtn}
          ${cancelSection}
        </div>
      `;
    }

    // 获取累计用时（秒）
    function getTotalTime(role, now) {
      if (role.isActive && role.lastStart && !isPaused) {
        return Math.floor(role.totalTime + (now - role.lastStart)/1000);
      } else {
        return Math.floor(role.totalTime);
      }
    }

    // 绑定事件
    function bindEvents() {
      // +1
      document.querySelectorAll('.btn-add').forEach(el => {
        el.onclick = function() {
          const idx = +el.dataset.idx;
          if (roles[idx].progress < MAX_TASKS) {
            roles[idx].progress++;
            saveData({roles});
            renderRoles();
          }
        };
      });
      // -1
      document.querySelectorAll('.btn-sub').forEach(el => {
        el.onclick = function() {
          const idx = +el.dataset.idx;
          if (roles[idx].progress > 0) {
            roles[idx].progress--;
            saveData({roles});
            renderRoles();
          }
        };
      });
      // 完成
      document.querySelectorAll('.btn-finish').forEach(el => {
        el.onclick = function() {
          const idx = +el.dataset.idx;
          // 记录完成前进度
          roles[idx].finishedProgress = roles[idx].progress;
          // 停止计时，累加用时
          if (roles[idx].isActive && roles[idx].lastStart) {
            roles[idx].totalTime += (Date.now() - roles[idx].lastStart) / 1000;
            roles[idx].lastStart = null;
          }
          roles[idx].isFinished = true;
          saveData({roles});
          renderRoles();
        };
      });
      // 还原
      document.querySelectorAll('.btn-restore').forEach(el => {
        el.onclick = function() {
          const idx = +el.dataset.idx;
          // 恢复为完成前的进度
          if (typeof roles[idx].finishedProgress === 'number') {
            roles[idx].progress = roles[idx].finishedProgress;
          }
          roles[idx].isFinished = false;
          roles[idx].finishedProgress = null;
          // 如果自然计时已结束（全部完成），还原后应恢复计时
          if (typeof dayTimerEnd === 'number' && dayTimerEnd) {
            dayTimerEnd = null;
            saveDayTimer();
          }
          saveData({roles});
          renderRoles();
        };
      });
      // 取消任务
      document.querySelectorAll('.btn-cancel').forEach(el => {
        el.onclick = function() {
          const idx = +el.dataset.idx;
          // 自动+1
          // if (roles[idx].progress < MAX_TASKS) {
          //   roles[idx].progress++;
          // }
          roles[idx].cancelUntil = Date.now() + CANCEL_TIME * 1000;
          saveData({roles});
          renderRoles();
        };
      });
    }

    // 切换进行中/未进行
    function switchRoles(row) {
      const leftIdx = row;
      const rightIdx = row + 5;
      const now = Date.now();
      // 左右互换isActive
      if (roles[leftIdx].isActive) {
        // 左->右，左暂停计时，右开始计时
        roles[leftIdx].isActive = false;
        if (roles[leftIdx].lastStart) {
          roles[leftIdx].totalTime += (now - roles[leftIdx].lastStart)/1000;
        }
        roles[leftIdx].lastStart = null;
        roles[rightIdx].isActive = true;
        roles[rightIdx].lastStart = now;
      } else {
        // 右->左，右暂停计时，左开始计时
        roles[rightIdx].isActive = false;
        if (roles[rightIdx].lastStart) {
          roles[rightIdx].totalTime += (now - roles[rightIdx].lastStart)/1000;
        }
        roles[rightIdx].lastStart = null;
        roles[leftIdx].isActive = true;
        roles[leftIdx].lastStart = now;
      }
      saveData({roles});
      renderRoles();
    }

    // 名字编辑逻辑
    function startEditName(idx) {
      const card = document.querySelector(`.role-card[data-idx="${idx}"]`);
      const nameDiv = card.querySelector('.role-name');
      const input = document.createElement('input');
      input.type = 'text';
      input.value = roles[idx].name;
      input.className = 'role-name editing';
      input.style.width = '90%';
      input.onblur = saveEdit;
      input.onkeydown = function(e) {
        if (e.key === 'Enter') input.blur();
      };
      nameDiv.replaceWith(input);
      input.focus();
      input.select();
      function saveEdit() {
        roles[idx].name = input.value.trim() || `角色${idx+1}`;
        saveData({roles});
        renderRoles();
      }
    }

    // 倒计时和计时器刷新
    setInterval(() => {
      let needUpdate = false;
      const now = Date.now();
      // 判断是否全部完成
      const allFinished = roles.every(r => r.isFinished);
      // 计时逻辑
      let showTime = 0;
      if (dayTimerEnd) {
        // 已经全部完成，显示最终耗时
        showTime = Math.floor((dayTimerEnd - dayTimerStart - dayTimerPaused) / 1000);
      } else if (allFinished) {
        // 第一次全部完成，记录结束时间
        dayTimerEnd = now;
        showTime = Math.floor((dayTimerEnd - dayTimerStart - dayTimerPaused) / 1000);
        saveDayTimer();
      } else if (isPaused) {
        // 暂停中
        if (dayTimerPauseStart) {
          showTime = Math.floor((dayTimerPauseStart - dayTimerStart - dayTimerPaused) / 1000);
        } else {
          showTime = Math.floor((now - dayTimerStart - dayTimerPaused) / 1000);
        }
      } else {
        // 正常计时
        showTime = Math.floor((now - dayTimerStart - dayTimerPaused) / 1000);
      }
      document.getElementById('day-total-time').textContent = formatTimeHMS(showTime);
      roles.forEach((role, idx) => {
        if (role.cancelUntil > 0 && role.cancelUntil <= now) {
          role.cancelUntil = 0;
          needUpdate = true;
        }
      });
      // 刷新倒计时显示
      document.querySelectorAll('.countdown').forEach(el => {
        const idx = +el.dataset.idx;
        const left = Math.max(0, Math.ceil((roles[idx].cancelUntil - now)/1000));
        el.textContent = formatTime(left);
      });
      // 刷新累计用时
      document.querySelectorAll('.role-timer').forEach((el, i) => {
        const idx = el.closest('.role-card').dataset.idx;
        if (roles[idx]) {
          el.textContent = formatTime(getTotalTime(roles[idx], now));
        }
      });
      if (needUpdate) {
        saveData({roles});
        renderRoles();
      }
    }, 1000);

    // 工具函数
    function formatTime(sec) {
      sec = Math.floor(sec);
      const m = Math.floor(sec/60);
      const s = sec%60;
      return `${m.toString().padStart(2,'0')}:${s.toString().padStart(2,'0')}`;
    }
    function formatTimeHMS(sec) {
      sec = Math.floor(sec);
      const h = Math.floor(sec/3600);
      const m = Math.floor((sec%3600)/60);
      const s = sec%60;
      return `${h.toString().padStart(2,'0')}:${m.toString().padStart(2,'0')}:${s.toString().padStart(2,'0')}`;
    }
    function escapeHtml(str) {
      return str.replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#39;'}[c]));
    }

    // 灰色完成样式
    const style = document.createElement('style');
    style.innerHTML = `.finished-role {\n  background: #e0e0e0 !important;\n  border: 2.5px solid #bdbdbd !important;\n  box-shadow: 0 4px 18px rgba(160,160,160,0.10) !important;\n  opacity: 1 !important;\n  min-height: 48px !important;\n  padding: 6px 2px 6px 2px !important;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n}\n@media (max-width: 600px) {\n  .finished-role {\n    min-height: 36px !important;\n  }\n}\n.finished-label {\n  color: #888;\n  font-size: 1.15em;\n  text-align: center;\n  margin: 4px 0 2px 0 !important;\n  font-weight: bold;\n  letter-spacing: 2px;\n}\n.btn-restore {\n  background: #fff;\n  color: #409eff;\n  border: 1.5px solid #409eff;\n  border-radius: 8px;\n  font-size: 1em;\n  font-weight: 600;\n  margin: 4px auto 0 auto !important;\n  display: block;\n  padding: 6px 18px;\n  cursor: pointer;\n  box-shadow: 0 1px 4px rgba(64,158,255,0.08);\n  transition: background 0.2s, color 0.2s;\n}\n.btn-restore:active {\n  background: #e6f7ff;\n}\n.finished-time {\n  color: #555;\n  font-size: 1.08em;\n  text-align: center;\n  margin: 2px 0 2px 0 !important;\n  font-weight: 500;\n}`;
    document.head.appendChild(style);

    // 今日总耗时（自然时间）相关
    const DAY_TIMER_KEY = 'xyq_shimen_day_timer_v2';
    let dayTimerStart = Date.now(); // 计时起点
    let dayTimerPaused = 0; // 累计暂停时长（毫秒）
    let dayTimerPauseStart = null; // 当前暂停开始时间戳
    let dayTimerEnd = null; // 全部完成时的时间戳
    function loadDayTimer() {
      const data = localStorage.getItem(DAY_TIMER_KEY);
      if (data) {
        try {
          const parsed = JSON.parse(data);
          dayTimerStart = parsed.dayTimerStart || Date.now();
          dayTimerPaused = parsed.dayTimerPaused || 0;
          dayTimerPauseStart = parsed.dayTimerPauseStart || null;
          dayTimerEnd = parsed.dayTimerEnd || null;
        } catch {}
      }
    }
    function saveDayTimer() {
      localStorage.setItem(DAY_TIMER_KEY, JSON.stringify({dayTimerStart, dayTimerPaused, dayTimerPauseStart, dayTimerEnd}));
    }
    loadDayTimer();

    // 首次渲染
    renderRoles();
    // 底部操作栏事件
    document.getElementById('btn-toggle-pause').onclick = function() {
      const now = Date.now();
      if (!isPaused) {
        // 开始暂停
        isPaused = true;
        pauseStartTime = now;
        this.textContent = '恢复';
        // 暂停时，所有未完成且正在计时的角色，累加用时并清空lastStart
        roles.forEach(role => {
          if (!role.isFinished && role.isActive && role.lastStart) {
            role.totalTime += (now - role.lastStart) / 1000;
            role.lastStart = null;
          }
        });
        // 记录暂停开始时间
        if (!dayTimerPauseStart) dayTimerPauseStart = now;
        saveData({roles});
        saveDayTimer();
      } else {
        // 恢复
        isPaused = false;
        if (pauseStartTime) {
          totalPausedTime += now - pauseStartTime;
        }
        pauseStartTime = null;
        this.textContent = '暂停';
        // 恢复时，所有未完成且isActive的角色，lastStart重新赋值为当前时间
        roles.forEach(role => {
          if (!role.isFinished && role.isActive && !role.lastStart) {
            role.lastStart = now;
          }
        });
        // 累加暂停时长
        if (dayTimerPauseStart) {
          dayTimerPaused += now - dayTimerPauseStart;
          dayTimerPauseStart = null;
        }
        saveData({roles});
        saveDayTimer();
      }
      savePause();
    };
    document.getElementById('btn-reset-all').onclick = function() {
      if (confirm('确定要重置所有角色进度和计时数据（保留角色名）吗？')) {
        // 只重置进度、用时等，不重置名字
        roles = roles.map((r, i) => ({
          name: r.name,
          progress: 0,
          cancelUntil: 0,
          isActive: i < 5,
          totalTime: 0,
          lastStart: i < 5 ? Date.now() : null,
          isFinished: false,
          finishedProgress: null,
          finishedTime: 0
        }));
        isPaused = false;
        pauseStartTime = null;
        totalPausedTime = 0;
        // 不重置今日总耗时
        saveData({roles});
        saveDayTimer(); // 重置自然计时
        document.getElementById('btn-toggle-pause').textContent = '暂停';
        renderRoles();
      }
    };
    document.getElementById('btn-clear-cache').onclick = function() {
      if (confirm('确定要彻底清空所有缓存并恢复初始状态吗？')) {
        localStorage.removeItem(STORAGE_KEY);
        localStorage.removeItem(PAUSE_KEY);
        localStorage.removeItem(DAY_TIMER_KEY);
        // 重新初始化自然计时
        dayTimerStart = Date.now();
        dayTimerPaused = 0;
        dayTimerPauseStart = null;
        dayTimerEnd = null;
        saveDayTimer();
        location.reload();
      }
    };
    // 样式
    const footerStyle = document.createElement('style');
    footerStyle.innerHTML = `.footer-bar {\n  width: 100vw;\n  max-width: 900px;\n  margin: 0 auto;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  gap: 18px;\n  background: #fafdff;\n  border-radius: 12px 12px 0 0;\n  box-shadow: 0 -2px 12px 0 rgba(64,158,255,0.06);\n  padding: 14px 0 10px 0;\n  position: fixed;\n  left: 50%;\n  bottom: 0;\n  transform: translateX(-50%);\n  z-index: 99;\n  height: 90px; /* 固定footer高度 */\n}\n.footer-bar button {\n  padding: 7px 18px;\n  border: none;\n  border-radius: 8px;\n  background: #409eff;\n  color: #fff;\n  cursor: pointer;\n  font-size: 1.13em;\n  font-weight: 600;\n  transition: background 0.2s, box-shadow 0.2s;\n  box-shadow: 0 1px 4px rgba(64,158,255,0.08);\n  outline: none;\n}\n.footer-bar button:active {\n  background: #337ecc;\n}\n.footer-bar .pause-timer {\n  color: #666;\n  font-size: 1.08em;\n  margin-left: 10px;\n  font-weight: 500;\n}\n#btn-clear-cache { background: #f56c6c; color: #fff; border: none; }\n#btn-clear-cache:active { background: #c0392b; }\n.day-total-timer { color: #222; font-size: 1.08em; font-weight: 600; margin-left: 10px; }`;
    document.head.appendChild(footerStyle);
  </script>
</body>
</html> 